package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.IBankAccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author SpongeBob
 */
@Service
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements IBankAccountService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BankAccountResDTO saveBank(BankAccountUpsertReqDTO bankAccountDTO) {
        BankAccount bankAccount = BeanUtil.toBean(bankAccountDTO, BankAccount.class);
        Long userId = UserContext.currentUserId();
        bankAccount.setId(userId);
        try {
            this.saveOrUpdate(bankAccount);
        } catch (Exception e) {
            throw new RuntimeException("保存机构银行信息失败");
        }
        return BeanUtil.toBean(bankAccount, BankAccountResDTO.class);

    }

    @Override
    public BankAccountResDTO getBank() {
        Long userId = UserContext.currentUserId();
        //根据用户id获取机构银行信息
        BankAccount bankAccount = baseMapper.selectById(userId);
        return BeanUtil.toBean(bankAccount, BankAccountResDTO.class);
    }

    @Override
    public BankAccountUpsertReqDTO currentUserBankAccount() {
        Long currentUserId = UserContext.currentUserId();
        BankAccount bankAccount = this.getById(currentUserId);
        if (ObjectUtil.isNotNull(bankAccount)) {
            return BeanUtil.toBean(bankAccount, BankAccountUpsertReqDTO.class);
        }
        return null;
    }

    @Override
    public void SettingsBankAccount(BankAccountUpsertReqDTO bankAccountUpsertReqDTO) {
        BankAccount bankAccount = BeanUtil.toBean(bankAccountUpsertReqDTO, BankAccount.class);
        Long currentUserId = UserContext.currentUserId();
        bankAccount.setId(currentUserId);
        this.saveOrUpdate(bankAccount);
    }
}
